package com.yanqu.road.server.cmd.union;

import com.yanqu.road.server.manager.union.CrossUnionConfigMgr;
import com.yanqu.road.server.manger.CrossUnionServerGroupMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.pb.CrossUnionPb;
import com.yanqu.road.pb.union.UnionProto;
import com.yanqu.road.server.cmd.CrossCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.manager.union.CrossUnionMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;

import java.util.Map;

@Cmd(code = Protocol.C_CROSS_QUERY_UNION, desc = "跨服商会信息")
public class CrossQueryUnionCmd extends CrossCommand {

    private long userId;

    private long watchServerId;

    private String watchUnionUid;

    private CrossUnionInfo crossUnionInfo;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        UnionProto.CrossUnionQueryReqMsg reqMsg = UnionProto.CrossUnionQueryReqMsg.parseFrom(packet.getBytes());
        userId = packet.getPlayerId();
        watchServerId = reqMsg.getServerId();
        watchUnionUid = reqMsg.getUnionUid();



        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {
        crossUnionInfo = CrossUnionMgr.getUnionInfo(watchUnionUid);
        if (crossUnionInfo == null) {
            ret = GameErrorCode.E_UNION_NO_FOUND;
        }
    }

    @Override
    public void sendData() {
        UnionProto.CrossUnionQueryFromServerRespMsg.Builder respMsg = UnionProto.CrossUnionQueryFromServerRespMsg.newBuilder();
        respMsg.setRet(ret);
        if(0 == ret){
            respMsg.setUserId(userId);
            respMsg.setServerId(serverId);
            respMsg.setUnion(CrossUnionPb.parseUnionTempMsg(crossUnionInfo));
            int crossServerCount = CrossUnionServerGroupMgr.getGroupServerCountByServerId(crossUnionInfo.getServerId());
            respMsg.setMaxMemberCount(CrossUnionConfigMgr.getMaxMemberCount(crossUnionInfo.getExperience(), crossUnionInfo.isCross(), crossServerCount));
            Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(crossUnionInfo.getUnionUid());
            if (null != memberMap) {
                for (CrossUnionMember member : memberMap.values()) {
                    UnionProto.UnionMemberTempMsg.Builder memberMsg = CrossUnionPb.parseUnionMemberTempMsg(member);
                    if(null != memberMsg) {
                        respMsg.addMemberList(memberMsg);
                    }
                }
            }
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_QUERY_UNION_RESP, respMsg);
        MessageHelper.sendPacket(serverId, userId, pbMsg);
    }
}
